/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.data.source;

import io.iec.edp.caf.commons.utils.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author wangyandong
 * @date 2020/04/22 上午 11:10
 *
 */
public class Utils {
    private final static byte[] KEYS = { 83,87,53,122,99,72,86,121,82,50,86,117,90,88,74,122,98,50,90,48,73,65,61,61 };
    private static String key = null;
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="planPasswd"></param>
    /// <returns></returns>
    public static String encrypt(String planPasswd)
    {
        try {
            String key = getLegalKey();
            String iv = getLegalKey();

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = planPasswd.getBytes();
            int plaintextLength = dataBytes.length;

            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return Base64Utils.encode(encrypted).trim();

        } catch (Exception e) {
            //throw new RuntimeException(e);
            return planPasswd;
        }
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="encryptedPasswd"></param>
    /// <returns></returns>
    public static String decrypt(String encryptedPasswd)
    {
        String key = getLegalKey();
        String iv = getLegalKey();

        try
        {
            byte[] encrypted1 = Base64Utils.decode(encryptedPasswd);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString.trim();
        }
        catch (Exception e) {
            //throw new RuntimeException(e);
            return encryptedPasswd;
        }
    }

    /// <summary>
    /// 获取合法密码
    /// </summary>
    /// <returns>合法密码</returns>
    private static String getLegalKey() {
        if(key==null){
            Base64.Decoder decoder = Base64.getDecoder();
            try {
                key = new String(decoder.decode(new String(KEYS)), "UTF-8");
            }
            catch(UnsupportedEncodingException e){
                e.printStackTrace();
            }
        }
        return key;
    }
}
